//
//  PublishViewController.m
//  xxShare
//
//  Created by 柳麟喆 on 2018/3/6.
//  Copyright © 2018年 lzLiu. All rights reserved.
//

#import "PublishViewController.h"
#import "LxGridViewFlowLayout.h"
#import "PublishCollectionViewCell.h"
#import "TZImagePickerController.h"
#import "UIView+LLZLayout.h"
#import "TagTableViewController.h"
#import "LocationTableViewController.h"
#import "FeedModel.h"

@interface PublishViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,TZImagePickerControllerDelegate,UITextViewDelegate>{
    
    CGFloat _margin;
    CGFloat _itemWH;
}

@property(nonatomic, strong) UICollectionView *collectionView;
@property(nonatomic, strong) LxGridViewFlowLayout *layout;
@property(nonatomic, strong) UITextView *textView;
@property(nonatomic, strong) UILabel *tagLabel;
@property(nonatomic, strong) UIImageView *tagImage;
@property(nonatomic, strong) UILabel *locationLabel;
@property(nonatomic, strong) UIImageView *locationImage;

@end

@implementation PublishViewController

#pragma mark - *******生命周期*******
- (void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"发布内容";
    self.view.backgroundColor = BACKGROUND_COLOR;
    
    UIBarButtonItem *left = [[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancelPublish)];
    self.navigationItem.leftBarButtonItem = left;
    
    UIBarButtonItem *right = [[UIBarButtonItem alloc]initWithTitle:@"发表" style:UIBarButtonItemStylePlain target:self action:@selector(publishs)];
    right.tintColor = [UIColor greenColor];
    self.navigationItem.rightBarButtonItem = right;

    [self configSubview];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(dealTag:) name:@"tagNotification" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(dealLocation:) name:@"locationNotification" object:nil];
}

#pragma mark - *******懒加载*******
- (NSMutableArray *)selectedAssets{
    if (!_selectedAssets) {
        _selectedAssets = [[NSMutableArray alloc]init];
    }
    return _selectedAssets;
}

- (NSMutableArray *)selectedPhotos{
    if (!_selectedPhotos){
        _selectedPhotos = [[NSMutableArray alloc]init];
    }
    return _selectedPhotos;
}

#pragma mark - *******导航栏按钮响应方法*******
- (void)cancelPublish{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)publishs{
    NSDictionary *dic = @{@"imageName":@"duck.png",
                          @"name":@"Kylin",
                          @"devote":@"90",
                          @"photos":@[@"风景11",@"风景12"],
                          @"postContent":_textView.text,
                          @"tags":@"风景",
                          @"location":@"杭州市",
                          @"time":@"刚刚",
                          @"moneyNum":@"0",
                          @"thumbNum":@"0",
                          @"commentNum":@"0",
                          };
    FeedModel *model = [[FeedModel alloc]initWithFeedModel:dic];
    [self dismissViewControllerAnimated:YES completion:^{
        [SVProgressHUD showSuccessWithStatus:@"发表成功！"];
        [SVProgressHUD dismissWithDelay:1.0];
        [[NSNotificationCenter defaultCenter]postNotificationName:@"postNotification" object:model];
    }];
    
}

#pragma mark - *******布局*******
///配置configSubview
- (void)configSubview{
    
    //textView
    _textView = [[UITextView alloc]init];
    _textView.frame = CGRectMake(0, 64, self.view.llz_width, 37.5);
    _textView.font = [UIFont systemFontOfSize:18.0f];
    _textView.delegate = self;
    _textView.scrollEnabled = NO;
    _textView.backgroundColor = BACKGROUND_COLOR;
    [self.view addSubview:_textView];
    
    // _placeholderLabel
    UILabel *placeHolderLabel = [[UILabel alloc] init];
    placeHolderLabel.text = @"说点什么吧😄";
    placeHolderLabel.numberOfLines = 0;
    placeHolderLabel.textColor = [UIColor lightGrayColor];
    [placeHolderLabel sizeToFit];
    [_textView addSubview:placeHolderLabel];
    placeHolderLabel.font = [UIFont systemFontOfSize:18.0f];
    [_textView setValue:placeHolderLabel forKey:@"_placeholderLabel"];
    
    // 如不需要长按排序效果，将LxGridViewFlowLayout类改成UICollectionViewFlowLayout即可
    self.layout = [[LxGridViewFlowLayout alloc] init];
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:self.layout];
    self.collectionView.alwaysBounceVertical = YES;
//    CGFloat rgb = 244 / 255.0;
//    self.collectionView.backgroundColor = [UIColor colorWithRed:rgb green:rgb blue:rgb alpha:1.0];
    self.collectionView.backgroundColor = BACKGROUND_COLOR;
    self.collectionView.contentInset = UIEdgeInsetsMake(4, 4, 4, 4);
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    self.collectionView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    [self.view addSubview:self.collectionView];
    [self.collectionView registerClass:[PublishCollectionViewCell class] forCellWithReuseIdentifier:@"PublishCollectionViewCell"];
    
    
    //tag image
    _tagImage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"标签.png"]];
    _tagImage.frame = CGRectMake(5, self.collectionView.llz_bottom + 30, 25, 25);
    [self.view addSubview:_tagImage];
    //tag label
    _tagLabel = [[UILabel alloc]initWithFrame:CGRectMake(_tagImage.llz_right + 5, self.collectionView.llz_bottom + 30, SCREEN_WIDTH - 60, 25)];
    _tagLabel.userInteractionEnabled = YES;
    _tagLabel.backgroundColor = BACKGROUND_COLOR;
    _tagLabel.text = @"  请选择标签";
    _tagLabel.textColor = [UIColor blackColor];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(chooseTag)];
    [_tagLabel addGestureRecognizer:tap];
    [self.view addSubview:_tagLabel];
    
    //location image
    _locationImage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"位置.png"]];
    _locationImage.frame = CGRectMake(5, self.tagImage.llz_bottom + 20, 25, 25);
    [self.view addSubview:_locationImage];
    //location label
    _locationLabel = [[UILabel alloc]initWithFrame:CGRectMake(_locationImage.llz_right + 5, self.tagLabel.llz_bottom + 20, SCREEN_WIDTH - 60, 25)];
    _locationLabel.userInteractionEnabled = YES;
    _locationLabel.backgroundColor = BACKGROUND_COLOR;
    _locationLabel.text = @"  所在位置";
    _locationLabel.textColor = [UIColor blackColor];
    UITapGestureRecognizer *tapLocation = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(chooseLocation)];
    [_locationLabel addGestureRecognizer:tapLocation];
    [self.view addSubview:_locationLabel];
    
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    _margin = 4;
    _itemWH = (self.view.llz_width - 2 * _margin - 4) / 3 - _margin;
    self.layout.itemSize = CGSizeMake(_itemWH, _itemWH);
    self.layout.minimumInteritemSpacing = _margin;
    self.layout.minimumLineSpacing = _margin;
    [self.collectionView setCollectionViewLayout:self.layout];
    self.collectionView.frame = CGRectMake(0, _textView.llz_bottom + 64, self.view.llz_width, (_itemWH + _margin) * ((self.selectedPhotos.count + 3) / 3) + _margin);
    
    //标签栏
    _tagImage.frame = CGRectMake(5, self.collectionView.llz_bottom + 30, 25, 25);
    _tagLabel.frame = CGRectMake(_tagImage.llz_right + 5, self.collectionView.llz_bottom + 30, SCREEN_WIDTH - 60, 25);
    
    //位置栏
    _locationImage.frame = CGRectMake(5, self.tagImage.llz_bottom + 20, 25, 25);
    _locationLabel.frame = CGRectMake(_locationImage.llz_right + 5, self.tagLabel.llz_bottom + 20, SCREEN_WIDTH - 60, 25);
}

#pragma mark - *******UITextViewDelegate*******
- (void)textViewDidChange:(UITextView *)textView{
    CGSize newSize = [_textView sizeThatFits:CGSizeMake(self.view.llz_width, 30)];
    if (newSize.height >= 120) {
        _textView.scrollEnabled = YES;
    }else{
        _textView.scrollEnabled = NO;
        _textView.frame = CGRectMake(0, 64, textView.llz_width, newSize.height);
    }
}

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}

#pragma mark UICollectionView
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.selectedPhotos.count + 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    PublishCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PublishCollectionViewCell" forIndexPath:indexPath];
    if (indexPath.row == self.selectedPhotos.count) {
        //添加按钮
        cell.imageView.image = [UIImage imageNamed:@"AlbumAddBtn.png"];
        cell.deleteBtn.hidden = YES;
    } else{
        //图片缩略图
        cell.imageView.image = self.selectedPhotos[indexPath.row];
        cell.asset = self.selectedAssets[indexPath.row];
        cell.deleteBtn.hidden = NO;
    }
    cell.deleteBtn.tag = indexPath.row;
    [cell.deleteBtn addTarget:self action:@selector(deleteBtnClik:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == self.selectedPhotos.count) {
        [self pushTZImagePickerController];
    } else{
     // preview photos / 预览照片
        TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithSelectedAssets:self.selectedAssets selectedPhotos:self.selectedPhotos index:indexPath.row];
        imagePickerVc.allowPickingOriginalPhoto = YES;//展示原图按钮
        imagePickerVc.showSelectBtn = YES;//展示是否选中的按钮
        imagePickerVc.isSelectOriginalPhoto = self.isSelectOriginalPhoto;
        [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
            self.selectedPhotos = [NSMutableArray arrayWithArray:photos];
            self.selectedAssets = [NSMutableArray arrayWithArray:assets];
            self.isSelectOriginalPhoto = isSelectOriginalPhoto;
            [self.collectionView reloadData];
//            self.collectionView.contentSize = CGSizeMake(0, ((self.selectedPhotos.count + 2) / 3 ) * (_margin + _itemWH));
            self.collectionView.frame = CGRectMake(0, _margin, self.view.llz_width, (_itemWH + _margin) * ((self.selectedPhotos.count + 3) / 3));
        }];
        [self presentViewController:imagePickerVc animated:YES completion:nil];
        
    }
}

#pragma mark - LxGridViewDataSource

/// 以下三个方法为长按排序相关代码
- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath {
    return indexPath.item < self.selectedPhotos.count;
}

- (BOOL)collectionView:(UICollectionView *)collectionView itemAtIndexPath:(NSIndexPath *)sourceIndexPath canMoveToIndexPath:(NSIndexPath *)destinationIndexPath {
    return (sourceIndexPath.item < self.selectedPhotos.count && destinationIndexPath.item < self.selectedPhotos.count);
}

- (void)collectionView:(UICollectionView *)collectionView itemAtIndexPath:(NSIndexPath *)sourceIndexPath didMoveToIndexPath:(NSIndexPath *)destinationIndexPath {
    UIImage *image = self.selectedPhotos[sourceIndexPath.item];
    [self.selectedPhotos removeObjectAtIndex:sourceIndexPath.item];
    [self.selectedPhotos insertObject:image atIndex:destinationIndexPath.item];
    
    id asset = self.selectedAssets[sourceIndexPath.item];
    [self.selectedAssets removeObjectAtIndex:sourceIndexPath.item];
    [self.selectedAssets insertObject:asset atIndex:destinationIndexPath.item];
    
    [self.collectionView reloadData];
}

#pragma mark - TZImagePickerController

- (void)pushTZImagePickerController {
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:9 columnNumber:4 delegate:self pushPhotoPickerVc:YES];
    imagePickerVc.isSelectOriginalPhoto = self.isSelectOriginalPhoto;
    imagePickerVc.selectedAssets = self.selectedAssets; // 目前已经选中的图片数组
    imagePickerVc.allowTakePicture = NO; // 在内部显示拍照按钮
    // You can get the photos by block, the same as by delegate.
    // 你可以通过block或者代理，来得到用户选择的照片.
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        self.selectedPhotos = [NSMutableArray arrayWithArray:photos];
        self.selectedAssets = [NSMutableArray arrayWithArray:assets];
        self.isSelectOriginalPhoto = isSelectOriginalPhoto;
        [self.collectionView reloadData];
//        self.collectionView.contentSize = CGSizeMake(0, ((self.selectedPhotos.count + 2) / 3 ) * (_margin + _itemWH));
        self.collectionView.frame = CGRectMake(0, _margin, self.view.llz_width, (_itemWH + _margin) * ((self.selectedPhotos.count + 3) / 3));
    }];
    
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}

#pragma mark - Click Event
- (void)deleteBtnClik:(UIButton *)sender {
    [self.selectedPhotos removeObjectAtIndex:sender.tag];
    [self.selectedAssets removeObjectAtIndex:sender.tag];
    
    [self.collectionView performBatchUpdates:^{
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:sender.tag inSection:0];
        [self.collectionView deleteItemsAtIndexPaths:@[indexPath]];
    } completion:^(BOOL finished) {
        [self.collectionView reloadData];
       self.collectionView.frame = CGRectMake(0, _margin, self.view.llz_width, (_itemWH + _margin) * ((self.selectedPhotos.count + 3) / 3));
    }];
}

#pragma mark - *******私有方法*******
- (void)chooseTag{
    TagTableViewController *tag = [[TagTableViewController alloc]init];
    [self.navigationController pushViewController:tag animated:YES];
}
///标签回调
- (void)dealTag:(NSNotification *)noti{
    NSMutableArray *array = noti.object;
    NSString *str = @"";
    for (int i = 0; i < array.count; i++) {
        str = [NSString stringWithFormat:@"%@"@"  #%@",str,array[i]];
    }
    _tagLabel.text = str;
}

- (void)chooseLocation{
    LocationTableViewController *loc = [[LocationTableViewController alloc]init];
    [self.navigationController pushViewController:loc animated:YES];
}
///位置回调
- (void)dealLocation:(NSNotification *)noti{
    _locationLabel.text = noti.object;
}
@end
